package com.wj.springboot2demo.mq;

import java.io.IOException;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;

/**
 * 消费者
 */
@Component
public class RabbitMqConsumer extends BabbitMqTest {

    
    @RabbitListener(
            //队列绑定信息
            bindings = @QueueBinding(
                    //队列信息：名称，通知方式
                    value = @Queue(value = "springboot2.queue", durable = "true"),
                    //绑定的交换器
                    exchange = @Exchange(value = "rabbitmq-1", durable = "true", type = "topic", ignoreDeclarationExceptions = "true"),

                    //routingKey
                    key = "springboot2"
                    )
            )
    @RabbitHandler
    public void onMessage(Message<Object> message, Channel channel) throws IOException {
        
        Long deliveryTag = 0L;
        
        try {
        	log("comsumer get message from producer");
            //包含消息内容，即Producer中放入的properties对象
            //包含消息内容，即Producer中放入的properties对象
            MessageHeaders headers = message.getHeaders();

            deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
            
            log("comsumer : deliveryTag " + deliveryTag);
            
            //
            log("comsumer : message.getPayload() " + message.getPayload());
            
            String id = (String) headers.get("msg_id");
            Long millis = (Long) headers.get("msg_millis");
            
            System.out.println(id);
            System.out.println(millis);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//        	log("comsumer act message");
        	
        	//手动ack
        	//第二个参数：是否批量ack
            channel.basicAck(deliveryTag, false);
        	
        	//手动拒绝，传入tagId，
        	//第二个参数：是否重新投递个消费者；
        	//false：则本消息结束；true：该消息会继续被消费者消费
//        	channel.basicReject(deliveryTag, true);
        }

    }
}
